#! /usr/bin/perl -w

package Task;

use Constants;

our $VERSION = 1.00;

sub new{
	my ($class) = @_;
	my $self = {
		_tid => undef,
		_output => undef,
		_executable => undef,
		_parameter=> undef,
		_logfile => undef
	};
	bless $self;
	return $self;
}

sub init{
   my ($self, $tid, $output, $logfile, $executable, $parameter) = @_;

	$self->{_tid} = $tid;
   $self->{_output} = $output;
	#redirect the stand output to the provided handle
   *STDOUT = $output;

   $self->{_executable} = $executable;
   $self->{_parameter} = $parameter;
   $self->{_logfile} = $logfile;
}

#exec is the main entry for every task
#it could select the correct implementation according to command

sub exec{
   my ($self) = @_;

	#execute the corresponding function according to executable name
	#executable functions could be defined in external package
	#include the external package containing executables
	my $executable = $self->{_executable};
	eval {
		&$executable();
	};

   if($@){
      $self->execute_dummy();
   }
}

sub execute_dummy {
	my($self) = @_;

	open LOGFILE, ">$self->{_logfile}";
   my $count = 0;

   while($count++ < 5)
   {
		print "$STATUS_TAG $self->{_tid}:$TASK_RUNNING:$count no executable found, choose dummy execution $self->{_parameter} $self->{_logfile}\n";
		print LOGFILE "$STATUS_TAG $self->{_tid}:$TASK_RUNNING:$count no executable found, choose dummy execution $self->{_parameter} $self->{_logfile}\n";
   	sleep 5;
   }
	close LOGFILE;
}

